from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4ProjectInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4ProjectInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class ProjectInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()
		
	def isPrereqProjectsDefined(self, iProject):
		objProjectInfo = gc.getProjectInfo(iProject)

		for iI in range(gc.getNumProjectInfos()):
			if(objProjectInfo.getProjectsNeeded(iI) > 0):
				return true
		return false

	def isVictoryThresholdsDefined(self, iProject):
		objProjectInfo = gc.getProjectInfo(iProject)

		for iI in range(gc.getNumVictoryInfos()):
			if(objProjectInfo.getVictoryThreshold(iI) != 0):
				return true
		return false
		
	def isBonusProductionModifiersDefined(self, iProject):
		objProjectInfo = gc.getProjectInfo(iProject)

		for iI in range(gc.getNumBonusInfos()):
			if(objProjectInfo.getBonusProductionModifier(iI) != 0):
				return true
		return false		
		
	def printProject(self, iProject):
		objProjectInfo = gc.getProjectInfo(iProject)

		szText = ""
		
		szText = appendString(szText,"		<ProjectInfo>")
		szText = appendString(szText,"			<Type>%s</Type>" %(objProjectInfo.getType()))
		szText = appendString(szText,"			<Description>%s</Description>" %(objProjectInfo.getTextKey()))
		szText = appendString(szText,"			<Civilopedia>%s</Civilopedia>" %(objProjectInfo.getCivilopediaKey()))
		szText = appendString(szText,"			<Strategy>%s</Strategy>" %(objProjectInfo.getStrategyKey()))

		if(objProjectInfo.getVictoryPrereq() != -1):
			szText = appendString(szText,"			<VictoryPrereq>%s</VictoryPrereq>" %(gc.getVictoryInfo(objProjectInfo.getVictoryPrereq()).getType()))
		else:
			szText = appendString(szText,"			<VictoryPrereq>NONE</VictoryPrereq>")

		if(objProjectInfo.getTechPrereq() != -1):
			szText = appendString(szText,"			<TechPrereq>%s</TechPrereq>" %(gc.getTechInfo(objProjectInfo.getTechPrereq()).getType()))
		else:
			szText = appendString(szText,"			<TechPrereq>NONE</TechPrereq>")

		if(objProjectInfo.getAnyoneProjectPrereq() != -1):
			szText = appendString(szText,"			<AnyonePrereqProject>%s</AnyonePrereqProject>" %(gc.getProjectInfo(objProjectInfo.getAnyoneProjectPrereq()).getType()))
		else:
			szText = appendString(szText,"			<AnyonePrereqProject>NONE</AnyonePrereqProject>")

		szText = appendString(szText,"			<iMaxGlobalInstances>%s</iMaxGlobalInstances>" %(objProjectInfo.getMaxGlobalInstances()))
		szText = appendString(szText,"			<iMaxTeamInstances>%s</iMaxTeamInstances>" %(objProjectInfo.getMaxTeamInstances()))
		szText = appendString(szText,"			<iCost>%s</iCost>" %(objProjectInfo.getProductionCost()))
		szText = appendString(szText,"			<iNukeInterception>%s</iNukeInterception>" %(objProjectInfo.getNukeInterception()))
		szText = appendString(szText,"			<iTechShare>%s</iTechShare>" %(objProjectInfo.getTechShare()))

		if(objProjectInfo.getEveryoneSpecialUnit() != -1):
			szText = appendString(szText,"			<EveryoneSpecialUnit>%s</EveryoneSpecialUnit>" %(gc.getSpecialUnitInfo(objProjectInfo.getEveryoneSpecialUnit()).getType()))
		else:
			szText = appendString(szText,"			<EveryoneSpecialUnit>NONE</EveryoneSpecialUnit>")

		if(objProjectInfo.getEveryoneSpecialBuilding() != -1):
			szText = appendString(szText,"			<EveryoneSpecialBuilding>%s</EveryoneSpecialBuilding>" %(gc.getSpecialBuildingInfo(objProjectInfo.getEveryoneSpecialBuilding()).getType()))
		else:
			szText = appendString(szText,"			<EveryoneSpecialBuilding>NONE</EveryoneSpecialBuilding>")
		
		szText = appendString(szText,"			<bSpaceship>%s</bSpaceship>" %(boolToInt(objProjectInfo.isSpaceship())))

		szText = appendString(szText,"			<Button>%s</Button>" %(objProjectInfo.getButton()))

		if(self.isPrereqProjectsDefined(iProject)):
			szText = appendString(szText,"			<PrereqProjects>")
			for iI in range(gc.getNumProjectInfos()):
				if(objProjectInfo.getProjectsNeeded(iI) > 0):
					szText = appendString(szText,"				<PrereqProject>")
					szText = appendString(szText,"					<ProjectType>%s</ProjectType>" %(gc.getProjectInfo(iI).getType()))
					szText = appendString(szText,"					<iNeeded>%s</iNeeded>" %(objProjectInfo.getProjectsNeeded(iI)))
					szText = appendString(szText,"				</PrereqProject>")

			szText = appendString(szText,"			</PrereqProjects>")
		else:
			szText = appendString(szText,"			<PrereqProjects/>")

		if(self.isVictoryThresholdsDefined(iProject)):
			szText = appendString(szText,"			<VictoryThresholds>")
			for iI in range(gc.getNumVictoryInfos()):
				if(objProjectInfo.getVictoryThreshold(iI) != 0):
					szText = appendString(szText,"				<VictoryThreshold>")
					szText = appendString(szText,"					<VictoryType>%s</VictoryType>" %(gc.getVictoryInfo(iI).getType()))
					szText = appendString(szText,"					<iThreshold>%s</iThreshold>" %(objProjectInfo.getVictoryThreshold(iI)))
					szText = appendString(szText,"				</VictoryThreshold>")

			szText = appendString(szText,"			</VictoryThresholds>")
		else:
			szText = appendString(szText,"			<VictoryThresholds/>")

		if(self.isBonusProductionModifiersDefined(iProject)):
			szText = appendString(szText,"			<BonusProductionModifiers>")
			for iI in range(gc.getNumBonusInfos()):
				if(objProjectInfo.getBonusProductionModifier(iI) != 0):
					szText = appendString(szText,"				<BonusProductionModifier>")
					szText = appendString(szText,"					<BonusType>%s</BonusType>" %(gc.getBonusInfo(iI).getType()))
					szText = appendString(szText,"					<iProductonModifier>%s</iProductonModifier>" %(objProjectInfo.getBonusProductionModifier(iI)))
					szText = appendString(szText,"				</BonusProductionModifier>")

			szText = appendString(szText,"			</BonusProductionModifiers>")
		else:
			szText = appendString(szText,"			<BonusProductionModifiers/>")

		if(len(objProjectInfo.getCreateSound()) > 0):
			szText = appendString(szText,"			<CreateSound>%s</CreateSound>" %(objProjectInfo.getCreateSound()))
		else:
			szText = appendString(szText,"			<CreateSound/>")

		if(len(objProjectInfo.getMovieArtDef()) > 0):
			szText = appendString(szText,"			<MovieDefineTag>%s</MovieDefineTag>" %(objProjectInfo.getMovieArtDef()))
		else:
			szText = appendString(szText,"			<MovieDefineTag/>")

		
		szText = appendString(szText,"		</ProjectInfo>")

		
			
		return szText

						
	def printProjects(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Units" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4ProjectInfo.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Project Infos -->")
		szText = appendString(szText,"<!-- You must have atleast one project in order for the game to load properly. -->")

		szText = appendString(szText,"<Civ4ProjectInfo xmlns=\"x-schema:CIV4GameInfoSchema.xml\">")
		szText = appendString(szText,"	<ProjectInfos>")
				
		for iProject in range(gc.getNumProjectInfos()):

			if(gc.getProjectInfo(iProject).isDeleted()):
				continue

			szText = appendString(szText,self.printProject(iProject))
			
						
		szText = appendString(szText,"	</ProjectInfos>")
		szText = appendString(szText,"</Civ4ProjectInfo>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\GameInfo")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\GameInfo\CIV4ProjectInfo.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
				
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

